'''
This file is part of DopplerShift.

    DopplerShift is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DopplerShift is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DopplerShift.  If not, see <http://www.gnu.org/licenses/>.
'''
from dopplershift.core.containers.mediator import getMediator
from dopplershift.collector.backends.auth import memcached, redis
from dopplershift.collector.backends import UnknownBackendType

def choose_picklers(ident):
    if ident == 'pickle':
        import pickle
        return pickle.loads
    import json
    return json.loads
def authenticate_factory():
    cfg = getMediator().get('CollectorConfig')
    settings = cfg.get_auth_service_settings()
    pattern = cfg.get("auth_key_pattern")
    pickler = cfg.get('auth_session_pickler')
    if pattern is None: pattern = '%s'
    cls = None
    if settings['protocol'] == 'memcached':
        cls = memcached.MemcachedAuthBackend
    elif settings['protocol'] == 'redis':
        cls = redis.RedisBasedBackend
    else:
        raise UnknownBackendType(settings['protocol'])
    backend = cls(**settings)
    backend.session_key_pattern = pattern
    backend.pickler = choose_picklers(pickler)
    return backend